package com.woodstick.controller;

import java.util.HashMap;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.baidu.aip.face.AipFace;


/**
 * <strong>Title : RecognitionController </strong>. <br>
 * <strong>Description : 人脸识别Controller.</strong> <br>
 * <strong>Create on : 2018年10月24日 13:28:00 </strong>. <br>
 * <p>
 * </p>
 * 
 * @version <strong>人脸识别</strong> <br>
 *          <br>
 *          <strong>修改历史: .</strong> <br>
 *          修改人 修改日期 修改描述<br>
 *          -------------------------------------------<br>
 *          <br>
 *          <br>
 */
@Controller
public class RecognitionController {
	
//	private static Logger logger = LoggerFactory.getLogger(RecognitionController.class);
	
	/**
	 * 返回识别页面
	 * @param model
	 * @return
	 */
	@RequestMapping("rec")
	public String rec(ModelMap model){
	    return RECOGNITION_PAGE;
	}
	/**
	 * 人脸识别
	 * @param image 人脸信息的图片，采用base64编码
	 * @param name 用户姓名
	 * @param request
	 * @return 识别结果字符串
	 * @throws JSONException
	 */
    @RequestMapping(value = "/calculate", method = {RequestMethod.POST})
    @ResponseBody
	public String calculate(@RequestParam(value = "image", required = true) String image,
			@RequestParam(value = "name", required = true) String name,HttpServletRequest request) throws JSONException {
    	  String answer;
      	  // 初始化一个AipFace
          AipFace client = new AipFace(APP_ID, API_KEY, SECRET_KEY);
          // 可选：设置网络连接参数
          client.setConnectionTimeoutInMillis(CONNECTION_TIMEOUT);
          client.setSocketTimeoutInMillis(SOCKET_TIMEOUT);
          String recName = null;
          if(!DEFAULT_NAME.equals(name)){
        	  registerFace(image, name, client);
          }else{
        	  recName = searchFace(image, client, recName);
          }
          JSONObject res = new JSONObject();
		  res.put(REC_NAME, recName);
          answer = res.toString();
      	return answer;
    }

    /**
     * 人脸搜索
     * @param image
     * @param client
     * @param recName
     * @return
     * @throws JSONException
     */
	private String searchFace(String image, AipFace client, String recName) throws JSONException {
		  // 传入可选参数调用接口
		  HashMap<String, String> options = new HashMap<String, String>(3);
		  options.put(QUALITY_CONTROL, NORMAL);
		  options.put(LIVENESS_CONTROL, LOW);
		  options.put(MAX_USER_NUM, NUM_THREE);
		  String imageType = BASE64;
		  String groupIdList = DEFAULT_GROUP;
		  // 人脸搜索
		  JSONObject res = client.search(image, imageType, groupIdList, options);
		  String resultStr = res.optString(RESULT);
		  if(!StringUtils.isEmpty(resultStr)){
			  JSONObject resultJson = res.getJSONObject(RESULT);
		      if(resultJson != null && resultJson.getJSONArray(USER_LIST) != null){
		    	  JSONArray userListJson = resultJson.getJSONArray(USER_LIST);
		    	  if(userListJson.length() > 0
		    			  && userListJson.getJSONObject(0).getDouble(SCORE) > SCORE_LOW_LIMIT){
		    		  String userInfoStr = userListJson.getJSONObject(0).getString(USER_INFO);
	        		  recName = userInfoStr;
		    	  }
		      }
		  }
		return recName;
	}

	/**
	 * 人脸注册
	 * @param image
	 * @param name
	 * @param client
	 */
	private void registerFace(String image, String name, AipFace client) {
		// 传入可选参数调用接口
		HashMap<String, String> options = new HashMap<String, String>(3);
		String userId = USERID_PREFIX+(UUID.randomUUID().toString().substring(4, 8));
		options.put(USER_INFO, name);
		options.put(QUALITY_CONTROL, NORMAL);
		options.put(LIVENESS_CONTROL, LOW);
		String imageType = BASE64;
		String groupId = DEFAULT_GROUP;
		// 人脸注册
		client.addUser(image, imageType, groupId, userId, options);
	}
    
    private static final String APP_ID = "11478790";
    private static final String API_KEY = "w2lSBzGxopuAsZ3O4PBcAPYl";
    private static final String SECRET_KEY = "Pzqw7GFwcciygj20BrfTgsbVb34aHGnx";
    private static final String RECOGNITION_PAGE = "recognition";
    private static final String DEFAULT_NAME = "default";
    private static final String USERID_PREFIX = "u";
    private static final String USER_INFO = "user_info";
    private static final String QUALITY_CONTROL = "quality_control";
    private static final String MAX_USER_NUM = "max_user_num";
    private static final String LIVENESS_CONTROL = "liveness_control";
    private static final String NORMAL = "NORMAL";
    private static final String LOW = "LOW";
    private static final String BASE64 = "BASE64";
    private static final String NUM_THREE = "3";
    private static final String DEFAULT_GROUP = "group1";
    private static final String RESULT = "result";
    private static final String SCORE = "score";
    private static final String USER_LIST = "user_list";
    private static final String REC_NAME = "recName";
    private static final int CONNECTION_TIMEOUT = 2000;
    private static final int SOCKET_TIMEOUT = 60000;
    private static final int SCORE_LOW_LIMIT = 80;
}
